package org.example.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 对同一个接口，可能会有几种不同的实现类，而默认只会采取帶注解的，不然会报错
 * applyJdbcTemplate in com.gwssi.config.DB2DataSourceConfig required a single bean, but 2 were found
 */
@Slf4j
@Configuration
@MapperScan(basePackages = {"org.example.mapper"}, sqlSessionFactoryRef = "clickhouseSqlSessionFactory")
public class ClickHouseConfig {
    @javax.annotation.Resource
    private ClickHouseJdbcParamConfig jdbcParamConfig;

    @Bean("clickDataSource")
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(jdbcParamConfig.getUrl());
        datasource.setDriverClassName(jdbcParamConfig.getDriverClassName());
        datasource.setInitialSize(jdbcParamConfig.getInitialSize());
        datasource.setMinIdle(jdbcParamConfig.getMinIdle());
        datasource.setMaxActive(jdbcParamConfig.getMaxActive());
        datasource.setMaxWait(jdbcParamConfig.getMaxWait());
        datasource.setUsername(jdbcParamConfig.getUsername());
        datasource.setPassword(jdbcParamConfig.getPassword());
        return datasource;
    }

//    @Bean("clickTransactionManager")
//    public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("clickDataSource") DataSource dataSource) {
//        return new DataSourceTransactionManager(dataSource);
//    }

    @Bean(name = "clickhouseSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate phoenixSqlSessionTemplate(@Qualifier(value = "clickhouseSqlSessionFactory") SqlSessionFactory phoenixSqlSessionFactory) {
        return new SqlSessionTemplate(phoenixSqlSessionFactory);
    }

    @Bean("clickhouseSqlSessionFactory")
    @Primary
    public SqlSessionFactory getSqlSessionManager(@Qualifier("clickDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(resolveMapperLocations());

        //空值返回
        bean.getObject().getConfiguration().setCallSettersOnNulls(true);
        return bean.getObject();
    }

    public org.springframework.core.io.Resource[] resolveMapperLocations() {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        List<String> mapperLocations = Lists.newArrayList();
        mapperLocations.add("classpath*:clickhouse/*.xml");
        mapperLocations.add("classpath*:mapper/*.xml");
        List<org.springframework.core.io.Resource> resources = Lists.newArrayList();
        mapperLocations.forEach(mapperLocation -> {
            org.springframework.core.io.Resource[] mappers = new org.springframework.core.io.Resource[0];
            try {
                mappers = resourcePatternResolver.getResources(mapperLocation);
            } catch (IOException e) {
                log.error("clickhouse数据源xml文件地址加载异常", e);
            }
            resources.addAll(Arrays.asList(mappers));
        });
        return resources.toArray(new org.springframework.core.io.Resource[0]);
    }
}
